package com.itboye.hutouben.choosecity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.hutouben.R;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.choosecity.db.DBManager;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.widget.FlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 城市列表
 */

public class CityListActivity extends BaseActivity {
    private BaseAdapter adapter;
    private ListView city_list;
    private TextView overlay;
    private MyLetterListView cityLetterListView;
    private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
    private String[] sections;// 存放存在的汉语拼音首字母
    private Handler handler;
    private OverlayThread overlayThread;
    private SQLiteDatabase database;
    private ArrayList<CityBean> mCityNames;
    private ImageView close_icon;
    private TextView gpsTv;
    EditText edit_inputcity;
    private FlowLayout area_container;
    private ArrayList<CityBean> arrayLitArea;// 区域列表
    private DBManager dbManager;
    public String city;
    int type = 1;//1、直辖市    2、城市
    boolean searchType = true;//true、根据 城市搜索店铺     false、根据地区搜索店铺

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);

        init();

        //退出登录的广播
        IntentFilter intentFilterExit = new IntentFilter(
                "city");
       registerReceiver(nichengBroadcastReceiver, intentFilterExit);

    }
    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
          finish();

        };
    };


    private void init() {
        setStatusBarColor(R.color.blue);
        close_icon.setOnClickListener(this);
        gpsTv = (TextView) findViewById(R.id.gpsTv);
        gpsTv.setText(SPUtils.get(this, null, Const.SELECT_CITY, "") + "");

        gpsTv.setOnClickListener(this);

        dbManager = new DBManager(this);
        dbManager.openDateBase();
        database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
                + DBManager.DB_NAME, null);

        mCityNames = getCityNames();
        cityLetterListView
                .setOnTouchingLetterChangedListener(new LetterListViewListener());
        alphaIndexer = new HashMap<String, Integer>();
        handler = new Handler();
        overlayThread = new OverlayThread();

        initOverlay();
        setAdapter(mCityNames);
        city_list.setOnItemClickListener(new CityListOnItemClick());
    }
    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }
    /**
     * 从数据库获取城市数据
     *
     * @return
     */
    private ArrayList<CityBean> getCityNames() {
        ArrayList<CityBean> names = new ArrayList<CityBean>();
        Cursor cursor = database.rawQuery(
                "SELECT * FROM T_City ORDER BY NameSort", null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            CityBean cityModel = new CityBean();
            cityModel.setCityName(cursor.getString(cursor
                    .getColumnIndex("CityName")));
            cityModel.setNameSort(cursor.getString(cursor
                    .getColumnIndex("NameSort")));
            names.add(cityModel);
        }
        return names;
    }
    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    private class LetterListViewListener implements
            MyLetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s) + 1;
                city_list.setSelection(position);
                overlay.setText(sections[position]);
                overlay.setVisibility(View.GONE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 1500);
            }
        }
    }
    /**
     * ListViewAdapter
     */
    private class ListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private List<CityBean> list;

        public ListAdapter(Context context, List<CityBean> list) {

            this.inflater = LayoutInflater.from(context);
            this.list = list;
            alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];

            for (int i = 0; i < list.size(); i++) {
                // 当前汉语拼音首字母
                // getAlpha(list.get(i));
                String currentStr = list.get(i).getNameSort();
                // 上一个汉语拼音首字母，如果不存在为“ ”
                String previewStr = (i - 1) >= 0 ? list.get(i - 1)
                        .getNameSort() : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = list.get(i).getNameSort();
                    alphaIndexer.put(name, i);
                    sections[i] = name;
                }
            }

        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_item, null);
                holder = new ViewHolder();
                holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.name.setText(list.get(position).getCityName());
            String currentStr = list.get(position).getNameSort();
            String previewStr = (position - 1) >= 0 ? list.get(position - 1)
                    .getNameSort() : " ";
            if (!previewStr.equals(currentStr)) {
                holder.alpha.setVisibility(View.VISIBLE);
                holder.alpha.setText(currentStr);
            } else {
                holder.alpha.setVisibility(View.GONE);
            }
            return convertView;
        }

        private class ViewHolder {
            TextView alpha;
            TextView name;
        }

    }
    /**
     * 为ListView设置适配器
     *
     * @param list
     */
    private void setAdapter(List<CityBean> list) {


        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headview = layoutInflater.inflate(R.layout.inculd_city_headview,
                null);
        area_container = (FlowLayout) headview
                .findViewById(R.id.area_container);

        String gpsCity = SPUtils.get(this, null, Const.SELECT_CITY, "")
                + "";
        if (gpsCity.equals("")) {
            // gpsTv.setText("杭州");
            gpsTv.setText("定位失败请重新定位");
        } else {
            gpsTv.setText(gpsCity);
        }


        city_list.addHeaderView(headview);
        if (list != null) {
            adapter = new ListAdapter(this, list);
            city_list.setAdapter(adapter);
        }

    }
    /**
     * 城市列表点击事件
     *
     * @author sy
     *
     */
    class CityListOnItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                                long arg3) {
            if (pos == 0) {
                return;
            }
            searchType=true;
            CityBean cityModel = (CityBean) city_list.getAdapter().getItem(
                    pos);
            city = cityModel.getCityName();
            SPUtils.put(CityListActivity.this, null,
                    Const.SELECT_CITY, cityModel.getCityName());
//            afterCitySelected(city);
            Intent intent=new Intent();
            intent.putExtra("choose",city);
            setResult(102, intent);
            finish();
            // city_list.smoothScrollToPosition(0);
            city_list.setSelection(0);// 设置选择项为第一项
        }

    }
    private void afterCitySelected(String city) {
        String cityCode = "";
        SPUtils.put(this, null, Const.SELECT_CITY, city);
        gpsTv.setText("重新定位");
        // Intent intent = new Intent();
        // intent.putExtra("choose", city);
        // setResult(102,intent);
        if (city.equals("重庆市") || city.equals("北京市") || city.equals("天津市")// 特殊直辖市
                || city.equals("上海市")) {
            type=1;
            // cityCode = dbManager.queryPriovinceNo(city);
            Cursor cursor = database.rawQuery(
                    "SELECT provinceID from hat_province where province = ?",
                    new String[] { city });
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    cityCode = cursor.getString(cursor
                            .getColumnIndexOrThrow("provinceID"));
                }
            }
            cityCode = cityCode.substring(0, cityCode.length() - 4);
            // Cursor
            // cursor2=database.rawQuery("SELECT provinceID from hat_province where province = ?",new
            // String[]{});

        } else {
            type=2;
            Cursor cursor = database.rawQuery(
                    "SELECT cityID from hat_city where city = ?",
                    new String[] { city });
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    cityCode = cursor.getString(cursor
                            .getColumnIndexOrThrow("cityID"));
                }
            }
            cursor.close();
            // cityCode = dbManager.queryCityNo(city);
        }

        arrayLitArea = queryArea(cityCode);
        if(arrayLitArea==null){
            area_container.setVisibility(View.GONE);
        }else{
            addArea(arrayLitArea);
        }
    }
    /***
     * 查询区域列表
     * @param
     * @return
     */
    public ArrayList<CityBean> queryArea(String cityNo) {
        Cursor cursor = null;
        ArrayList<CityBean> arrayArea = new ArrayList<>();
        if (database != null)
            cursor = database.query("hat_area", null, "father like ?",
                    new String[] { cityNo + "%" }, null, null, null);
        if (cursor != null)
            while (cursor.moveToNext()) {
                CityBean cityModel = new CityBean();
                cityModel.setAreaCode(cursor.getString(cursor
                        .getColumnIndexOrThrow("areaID")));
                cityModel.setCityCode(cursor.getString(cursor
                        .getColumnIndexOrThrow("father")));
                cityModel.setAreaName(cursor.getString(cursor
                        .getColumnIndexOrThrow("area")));
                arrayArea.add(cityModel);
            }
        cursor.close();
        return arrayArea;
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void addArea(ArrayList<CityBean> array) {
        area_container.removeAllViews();
        for (int i = 0; i < array.size(); i++) {
            CityBean array_element = array.get(i);
            final TextView textView = new TextView(this);

            textView.setText(array_element.getAreaName());
            textView.setTag(array_element.getAreaCode());
            textView.setTextSize(15);
            textView.setPadding(10, 10, 10, 10);
            textView.setBackground(getResources().getDrawable(
                    R.drawable.btn_choose_city));
            android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(5, 5, 5, 5);


            area_container.addView(textView,
                    area_container.getChildCount() - 1, layoutParams);
            textView.setTag(R.id.tag_first, array_element.getAreaName());
            textView.setTag(R.id.tag_second, array_element.getAreaCode());

            textView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    searchType=false;
                    SPUtils.put(CityListActivity.this, null,
                            Const.SELECT_AREA,
                            textView.getTag(R.id.tag_first) + "");
                    Log.v("cityId", textView.getTag(R.id.tag_second) + "");
                    SPUtils.put(CityListActivity.this, null,
                            Const.SELECT_AREA_CODE,
                            textView.getTag(R.id.tag_second) + "");
                    Intent intent = new Intent();
                    intent.putExtra("choose",
                            city + "" + textView.getTag(R.id.tag_first));
                    intent.putExtra("areaCode",
                            textView.getTag(R.id.tag_second) + "");
                    intent.putExtra("type", type);
                    intent.putExtra("searchType", searchType);
                    setResult(102, intent);
                    finish();
                }
            });
        }
    }
    @Override
    protected void onInit() {

    }
    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if (arg0 == 101 && arg1 == 102) {
            Intent data=new Intent();
            data.putExtra("choose", arg2.getStringExtra("city"));
            setResult(102,data);
            finish();
        }
    }
    public static void goToCityListActivity(Context context) {
        Intent intent = new Intent(context, CityListActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close_icon:
                finish();
                break;
            case R.id.edit_inputcity:
                Intent intent = new Intent(CityListActivity.this,
                        ChooseCityActivity.class);
                startActivityForResult(intent, 101);
                break;
            default:
                break;
        }
    }
}
